"""
超级管理员相关API端点
"""
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from passlib.context import CryptContext

from app.database import get_db
from app.models.employee import Employee
from app.models.department import Department
from app.schemas.admin import CreateSuperAdminRequest, SuperAdminResponse

router = APIRouter()

# 密码加密上下文
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


@router.post("/create-super-admin", response_model=SuperAdminResponse)
def create_super_admin(
    *,
    db: Session = Depends(get_db),
    admin_data: CreateSuperAdminRequest
) -> Any:
    """
    创建超级管理员账户
    """
    # 检查是否已存在超级管理员
    existing_admin = db.query(Employee).filter(
        Employee.employee_no == admin_data.employee_no
    ).first()
    
    if existing_admin:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="该员工编号已存在"
        )
    
    # 获取或创建超级管理员部门
    admin_department = db.query(Department).filter(
        Department.name == "超级管理员部门"
    ).first()
    
    if not admin_department:
        admin_department = Department(
            name="超级管理员部门",
            description="系统超级管理员专用部门"
        )
        db.add(admin_department)
        db.commit()
        db.refresh(admin_department)
    
    # 创建超级管理员
    super_admin = Employee(
        employee_no=admin_data.employee_no,
        name=admin_data.name,
        department_id=admin_department.id,
        position="超级管理员",
        phone=admin_data.phone,
        email=admin_data.email,
        password_hash=pwd_context.hash(admin_data.password),
        status="active"
    )
    
    db.add(super_admin)
    db.commit()
    db.refresh(super_admin)
    
    return {
        "id": super_admin.id,
        "employee_no": super_admin.employee_no,
        "name": super_admin.name,
        "department_name": admin_department.name,
        "position": super_admin.position,
        "phone": super_admin.phone,
        "email": super_admin.email,
        "status": super_admin.status,
        "created_at": super_admin.created_at.isoformat() if super_admin.created_at else None
    }


@router.get("/super-admins", response_model=list[SuperAdminResponse])
def get_super_admins(
    db: Session = Depends(get_db)
) -> Any:
    """
    获取所有超级管理员列表
    """
    # 查找超级管理员部门的员工
    admin_department = db.query(Department).filter(
        Department.name == "超级管理员部门"
    ).first()
    
    if not admin_department:
        return []
    
    super_admins = db.query(Employee).filter(
        Employee.department_id == admin_department.id
    ).all()
    
    return [
        {
            "id": admin.id,
            "employee_no": admin.employee_no,
            "name": admin.name,
            "department_name": admin_department.name,
            "position": admin.position,
            "phone": admin.phone,
            "email": admin.email,
            "status": admin.status,
            "created_at": admin.created_at.isoformat() if admin.created_at else None
        }
        for admin in super_admins
    ]


@router.delete("/super-admin/{employee_id}")
def delete_super_admin(
    employee_id: int,
    db: Session = Depends(get_db)
) -> Any:
    """
    删除超级管理员
    """
    admin = db.query(Employee).filter(Employee.id == employee_id).first()
    
    if not admin:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="超级管理员不存在"
        )
    
    # 检查是否是超级管理员部门
    if admin.department.name != "超级管理员部门":
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="该用户不是超级管理员"
        )
    
    db.delete(admin)
    db.commit()
    
    return {"message": "超级管理员删除成功"}


@router.post("/reset-super-admin-password")
def reset_super_admin_password(
    employee_no: str,
    new_password: str,
    db: Session = Depends(get_db)
) -> Any:
    """
    重置超级管理员密码
    """
    admin = db.query(Employee).filter(Employee.employee_no == employee_no).first()
    
    if not admin:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="超级管理员不存在"
        )
    
    # 检查是否是超级管理员部门
    if admin.department.name != "超级管理员部门":
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="该用户不是超级管理员"
        )
    
    # 更新密码
    admin.password_hash = pwd_context.hash(new_password)
    db.commit()
    
    return {"message": "密码重置成功"}
